package jun.empdepmanagersystem02.filter;

import jun.empdepmanagersystem02.pojo.Result;
import jun.empdepmanagersystem02.until.JWTuntils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")

public class LoginCheckFillter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getRequestURL().toString().contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        System.out.println("拦截到了");
        Result result;
        if ((result = JWTuntils.verify(request.getHeader("token"))).getCode() == 1) {
            System.out.println("登录成功");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

//       重点 一定要按照需求文档来开发 返回内容的结构一定要一样 null也不能省略！！
        Gson gson = new GsonBuilder()
                .serializeNulls()
                .create();
        servletResponse.setContentType("application/json;charset=utf-8");
        servletResponse.getWriter().write(gson.toJson(result));
    }


    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
